//
//  ShareManager+JR.m
//  KidReading
//
//  Created by YangShuai on 16/6/28.
//  Copyright © 2016年 刘赞黄Telen. All rights reserved.
//

#import "ShareManager+JR.h"
#import "ConstDefine.h"

@interface ShareManager ()
@property(nonatomic,copy)void(^successBlock)(NSDictionary* retDict);
@property(nonatomic,copy)void(^failureBlock)(NSError* error);
@end


@implementation ShareManager (JR)

ASSOCIATED(successBlock, setSuccessBlock, id, OBJC_ASSOCIATION_COPY_NONATOMIC);
ASSOCIATED(failureBlock, setFailureBlock, id, OBJC_ASSOCIATION_COPY_NONATOMIC);

+(void)load{
    [self swizzleSelector:NSSelectorFromString(@"dealloc") withSelector:@selector(dealloc_shareJR)];
}

//分享方法(包含分享到发现)
//分享方法
static NSString* actCode_chant = @"chant";
static NSString* actCode_audioBottle = @"audioBottle";
-(void)JRShareContainExplorWithText:(NSString*)text ImageArray:(NSArray*)imageArray Url:(NSURL*)shareUrl Title:(NSString*)title Type:(SSDKContentType)type BaseView:(UIView*)baseView BookId:(NSInteger)bookId Success:(void (^)(NSDictionary * retDict))success failure:(void (^)(NSError *error))failure statusChange:(void (^)(SSDKResponseState state, SSDKPlatformType type))statuChange{
//    [DataProcessing do_Main_quick:^{
//        //
//        self.successBlock = success;
//        self.failureBlock = failure;
//        //
//        SSUIShareActionSheetCustomItem* item_bottle = [SSUIShareActionSheetCustomItem itemWithIcon:[UIImage imageNamed:@"icon_share_bottle.png"] label:NSLocalizedString(@"recordShareTo_Bottle", "") onClick:^{
//            [[NetGetPostsWithCache shareInstance] shareToExploreWithBookId:bookId ActCode:actCode_audioBottle ShareTitle:@"" Success:^(NSDictionary *retDict) {
//                if (success) success(retDict);
//            } failure:^(NSError *error) {
//                if (failure) failure(error);
//            }];
//        }];
//        //
//        SSUIShareActionSheetCustomItem *item_chant = [SSUIShareActionSheetCustomItem itemWithIcon:[UIImage imageNamed:@"icon_share_read.png"] label:NSLocalizedString(@"recordShareTo_Reading", "") onClick:^{
//            [self showShareReadingAlertViewAndhShareAction];
//        }];
//        //
//        NSArray * platforms =@[@(SSDKPlatformTypeSinaWeibo), @(SSDKPlatformTypeQQ), @(SSDKPlatformTypeWechat), @(SSDKPlatformTypeFacebook)];
//        if ([ReadBookVOrH_VC currentReadInstance].readerInsideOperMap) {
//            NSMutableArray *platforms_mu = [NSMutableArray arrayWithArray:platforms];
//            NSArray *operShareBtns = [ReadBookVOrH_VC currentReadInstance].readerInsideOperMap[@"shareBtns"];
//            NSInteger index = 0;
//            for (NSDictionary* btnDict in operShareBtns) {
//                NSString *code = btnDict[@"code"];
//                if ([code isEqualToString:@"audioBottle"]) {
//                    [platforms_mu insertObject:item_bottle atIndex:index];
//                    index ++;
//                }
//                if ([code isEqualToString:@"chant"]) {
//                    [platforms_mu insertObject:item_chant atIndex:index];
//                    index ++;
//                }
//            }
//            platforms = platforms_mu;
//        }
//        //
//        if ([self hasWhatsApp]) {
//            SSUIShareActionSheetCustomItem* item_whatApp = [SSUIShareActionSheetCustomItem itemWithIcon:[UIImage imageNamed:@"sns_icon_whatapp.png"] label:NSLocalizedString(@"whatsapp", "") onClick:^{
//                //
//                [self whatsAppSendText:[shareUrl absoluteString]];
//            }];
//            NSMutableArray *platforms_mu = [NSMutableArray arrayWithArray:platforms];
//            [platforms_mu addObject:item_whatApp];
//            platforms = platforms_mu;
//        }
//        
//        //再把声明的platforms对象传进分享方法里的items参数里
//        NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
//        [shareParams SSDKSetupShareParamsByText:text
//                                         images:imageArray
//                                            url:shareUrl
//                                          title:title
//                                           type:type];
//        //单独设置新浪微博分享方式
//        [shareParams SSDKSetupSinaWeiboShareParamsByText:[NSString stringWithFormat:@"%@ %@",text,shareUrl] title:title image:imageArray url:shareUrl latitude:0 longitude:0 objectID:nil type:SSDKContentTypeAuto];
//        [shareParams SSDKSetupFacebookParamsByText:[NSString stringWithFormat:@"%@ %@",text,shareUrl] image:imageArray type:SSDKContentTypeAuto];
//        //2、分享（可以弹出我们的分享菜单和编辑界面）
//        SSUIShareActionSheetController *sheet = [ShareSDK showShareActionSheet:baseView //要显示菜单的视图, iPad版中此参数作为弹出菜单的参照视图，只有传这个才可以弹出我们的分享菜单，可以传分享的按钮对象或者自己创建小的view 对象，iPhone可以传nil不会影响
//                                                                         items:platforms
//                                                                   shareParams:shareParams
//                                                           onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
//                                                               
//                                                               if (statuChange) {
//                                                                   statuChange(state,platformType);
//                                                               }
//                                                               
//                                                               switch (state) {
//                                                                   case SSDKResponseStateBegin:
//                                                                   {
//                                                                       [[NetGetPostsWithCache shareInstance] shareToOthersWithBookId:bookId Success:nil failure:nil];
//                                                                       //
//                                                                       break;
//                                                                   }
//                                                                   case SSDKResponseStateSuccess:
//                                                                   {
//                                                                       //
//                                                                       UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"talkSharesuccess","")
//                                                                                                                           message:nil
//                                                                                                                          delegate:nil
//                                                                                                                 cancelButtonTitle:NSLocalizedString(@"sure", "")
//                                                                                                                 otherButtonTitles:nil];
//                                                                       [alertView show];
//                                                                       break;
//                                                                   }
//                                                                   case SSDKResponseStateFail:
//                                                                   {
//                                                                       UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"talkSharefail","")
//                                                                                                                       message:nil
//                                                                                                                      delegate:nil
//                                                                                                             cancelButtonTitle:NSLocalizedString(@"sure", "")
//                                                                                                             otherButtonTitles:nil, nil];
//                                                                       [alert show];
//                                                                       break;
//                                                                   }
//                                                                   default:
//                                                                       break;
//                                                               }
//                                                           }
//                                                 ];
//        [sheet.directSharePlatforms addObject:@(SSDKPlatformTypeSinaWeibo)];
//        [sheet.directSharePlatforms addObject:@(SSDKPlatformTypeFacebook)];
//        
//    }];
}

-(void)JRSharePhotoContainExplorWithText:(NSString*)text ImageArray:(NSArray*)imageArray Url:(NSURL*)shareUrl Title:(NSString*)title Type:(SSDKContentType)type BaseView:(UIView*)baseView BookId:(NSInteger)bookId ActivityId:(NSInteger)activityId HurdleNo:(NSInteger)hurdleNo Success:(void (^)(NSDictionary * retDict))success failure:(void (^)(NSError *error))failure statusChange:(void (^)(SSDKResponseState state, SSDKPlatformType type))statuChange{
//    
//    [DataProcessing do_Main_quick:^{
//        
//        SSUIShareActionSheetCustomItem* item = [SSUIShareActionSheetCustomItem itemWithIcon:[UIImage imageNamed:@"icon_discover.png"] label:NSLocalizedString(@"explore", "") onClick:^{
//            [[NetGetPostsWithCache shareInstance] sharePhotoToExplorWithBookId:bookId ActivityId:activityId HurdleNo:hurdleNo Success:^(NSDictionary *retDict) {
//                if (success) success(retDict);
//            } Failure:^(NSError *error) {
//                if (failure) failure(error);
//            }];
//        }];
//        
//        NSArray * platforms =@[item,@(SSDKPlatformTypeSinaWeibo), @(SSDKPlatformTypeQQ), @(SSDKPlatformTypeWechat), @(SSDKPlatformTypeFacebook)];
//        //
//        if ([self hasWhatsApp]) {
//            SSUIShareActionSheetCustomItem* item_whatApp = [SSUIShareActionSheetCustomItem itemWithIcon:[UIImage imageNamed:@"sns_icon_whatapp.png"] label:NSLocalizedString(@"whatsapp", "") onClick:^{
//                //
//                [self whatsAppSendText:[shareUrl absoluteString]];
//            }];
//            
//            platforms =@[item,@(SSDKPlatformTypeSinaWeibo), @(SSDKPlatformTypeQQ), @(SSDKPlatformTypeWechat), @(SSDKPlatformTypeFacebook),item_whatApp];
//        }
//        //再把声明的platforms对象传进分享方法里的items参数里
//        
//        NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
//        [shareParams SSDKSetupShareParamsByText:text
//                                         images:imageArray
//                                            url:shareUrl
//                                          title:title
//                                           type:type];
//        //单独设置新浪微博分享方式
//        [shareParams SSDKSetupSinaWeiboShareParamsByText:[NSString stringWithFormat:@"%@ %@",text,shareUrl] title:title image:imageArray url:shareUrl latitude:0 longitude:0 objectID:nil type:SSDKContentTypeAuto];
//        [shareParams SSDKSetupFacebookParamsByText:[NSString stringWithFormat:@"%@ %@",text,shareUrl] image:imageArray type:SSDKContentTypeAuto];
//        //2、分享（可以弹出我们的分享菜单和编辑界面）
//        SSUIShareActionSheetController *sheet = [ShareSDK showShareActionSheet:baseView //要显示菜单的视图, iPad版中此参数作为弹出菜单的参照视图，只有传这个才可以弹出我们的分享菜单，可以传分享的按钮对象或者自己创建小的view 对象，iPhone可以传nil不会影响
//                                                                         items:platforms
//                                                                   shareParams:shareParams
//                                                           onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
//                                                               
//                                                               if (statuChange) {
//                                                                   statuChange(state,platformType);
//                                                               }
//                                                               
//                                                               switch (state) {
//                                                                   case SSDKResponseStateBegin:
//                                                                   {
//                                                                       [[NetGetPostsWithCache shareInstance] shareToOthersWithBookId:bookId Success:nil failure:nil];
//                                                                       break;
//                                                                   }
//                                                                   case SSDKResponseStateSuccess:
//                                                                   {
//                                                                       //
//                                                                       UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"talkSharesuccess","")
//                                                                                                                           message:nil
//                                                                                                                          delegate:nil
//                                                                                                                 cancelButtonTitle:NSLocalizedString(@"sure", "")
//                                                                                                                 otherButtonTitles:nil];
//                                                                       [alertView show];
//                                                                       break;
//                                                                   }
//                                                                   case SSDKResponseStateFail:
//                                                                   {
//                                                                       UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"talkSharefail","")
//                                                                                                                       message:nil
//                                                                                                                      delegate:nil
//                                                                                                             cancelButtonTitle:NSLocalizedString(@"sure", "")
//                                                                                                             otherButtonTitles:nil, nil];
//                                                                       [alert show];
//                                                                       break;
//                                                                   }
//                                                                   default:
//                                                                       break;
//                                                               }
//                                                           }
//                                                 ];
//        [sheet.directSharePlatforms addObject:@(SSDKPlatformTypeSinaWeibo)];
//        [sheet.directSharePlatforms addObject:@(SSDKPlatformTypeFacebook)];
//        
//    }];
}

//js按照dict返回的格式分享
-(void)JSShareWithJSDict:(NSDictionary*)jsDict ShowView:(UIView*)showView{
//    WebViewController* webC = [self parentControllerWithView:showView];
//    UIView *baseView = webC.rightBtn;
//    if (!webC.rightBtn) {
//        NoNaviWebViewController *noNaviWVC = [self parentNoNaviWebVCWithView:showView];
//        baseView = [noNaviWVC shareTrackView];
//    }
//    [self JRShareWithText:jsDict[@"desc"] ImageArray:@[jsDict[@"img"]] Url:[NSURL URLWithString:jsDict[@"value"]] Title:jsDict[@"title"] Type:SSDKContentTypeAuto BaseView:baseView statusChange:nil];
}

//-(NoNaviWebViewController*)parentNoNaviWebVCWithView:(UIView*)view{
//    UIResponder *responder = [view nextResponder];
//    while (responder) {
//        if ([responder isKindOfClass:[NoNaviWebViewController class]]) {
//            return (NoNaviWebViewController*)responder;
//        }
//        responder = [responder nextResponder];
//    }
//    return nil;
//}
//
//-(WebViewController*)parentControllerWithView:(UIView*)view{
//    UIResponder *responder = [view nextResponder];
//    while (responder) {
//        if ([responder isKindOfClass:[WebViewController class]]) {
//            return (WebViewController*)responder;
//        }
//        responder = [responder nextResponder];
//    }
//    return nil;
//}
//诵读alertView
-(UIAlertView*)showShareReadingAlertViewAndhShareAction{
    UIAlertView *recordNameAlertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"recordName", "") message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"recordShareCancel", "") otherButtonTitles:NSLocalizedString(@"recordShareSure", ""), nil];
    recordNameAlertView.alertViewStyle = UIAlertViewStylePlainTextInput;
    UITextField *textField = [recordNameAlertView textFieldAtIndex:0];
    textField.delegate = self;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChanged:) name:UITextFieldTextDidChangeNotification object:textField];
    textField.placeholder = NSLocalizedString(@"recordNamePlaceholder", "");
    [recordNameAlertView show];
    return recordNameAlertView;
}

#pragma mark - AlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        UITextField *textField = [alertView textFieldAtIndex:0];
        if (textField.text.length > 0) {
            //走接口
            [[NetGetPostsWithCache shareInstance] shareToExploreWithBookId:[ReadBookVOrH_VC currentReadInstance].bookid ActCode:actCode_chant ShareTitle:textField.text Success:^(NSDictionary *retDict) {
                if (self.successBlock) {
                    self.successBlock(retDict);
                }
            } failure:^(NSError *error) {
                if (self.failureBlock) {
                    self.failureBlock(error);
                }
            }];
        }else{
            [DataProcess do_Main:^{
                UIAlertView* nameAlertView = [self showShareReadingAlertViewAndhShareAction];
                [DataProcess do_Main:^{
                    [[[AFViewShaker alloc] initWithView:[nameAlertView textFieldAtIndex:0]] shake];
                } delay:0.1];
            } delay:0.1];
        }
    }
}

#pragma mark - TextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (string.length > 0) {
        if (toBeString.length > 20) {
            return NO;
        }
    }
    return YES;
}

//观察者方法
- (void)textFieldChanged:(id)sender
{
//    NSNotification* noti = (NSNotification*)sender;
//    UITextField* textField = noti.object;
//    if (textField.text.length >20) {
//        
//        if ([WYSDKManager isLowerThaniOS7]) {
//            [textField deleteBackward];
//        }else {
//            if ([WYSDKManager isContainsEmoji:[textField.text substringFromIndex:19]]) {
//                textField.text = [textField.text substringWithRange:NSMakeRange(0, 19)];
//            }else {
//                textField.text = [textField.text substringWithRange:NSMakeRange(0, 20)];
//            }
//        }
//        
//    }
}

-(void)dealloc_shareJR{
    [self dealloc_shareJR];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}


@end
